package com.cnpinxi.controller.web.pay;

import com.cnpinxi.controller.base.BaseController;
import com.cnpinxi.def.Constant;
import com.cnpinxi.domain.ConsigneeInfo;
import com.cnpinxi.domain.Order;
import com.cnpinxi.domain.PayParameter;
import com.cnpinxi.domain.User;
import com.cnpinxi.myRunTime.MyRunTimeExcption;
import com.cnpinxi.result.ResultObj;
import com.cnpinxi.service.ConsigneeInfoService;
import com.cnpinxi.service.OrderService;
import com.cnpinxi.service.PayService;
import com.cnpinxi.service.WeChatPayServiceImpl;
import com.cnpinxi.util.TwoDimensionCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by baggio on 2016/12/29.
 */
@RequestMapping("/pay")
@Controller
public class PayController extends BaseController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private PayService aliPayService;
    @Autowired
    private PayService weChatPayService;    @Autowired
    private ConsigneeInfoService consigneeInfoService;

    @RequestMapping(value = "/toPay")
    @ResponseBody
    public String toPay(HttpServletRequest request, Long orderId,  String paymentListJSON, ConsigneeInfo consigneeInfo) {
        ResultObj resultObj = new ResultObj();
        resultObj.setCode(ResultObj.CODE_SUCCESS);
        try {
            User user=(User)request.getSession().getAttribute(Constant.SESSION_KEY_USER_LOGIN);
            if(user==null){
                throw new MyRunTimeExcption("用户没有登录！");
            }
            String remoteAddr = request.getRemoteAddr();
            System.out.println("remoteAddr===>" + remoteAddr);
            String openid = (String) request.getSession().getAttribute("openId");
            logger.info("openId===>" + openid);
            consigneeInfoService.modifyConsigneeInfo(consigneeInfo);
            List<PayParameter>  payParameterList= orderService.toPay(orderId, paymentListJSON, remoteAddr, openid);
            resultObj.setData(payParameterList);
        } catch (MyRunTimeExcption runTimeExcption) {
            logger.info(runTimeExcption.getMessage());
            resultObj.setCode(ResultObj.CODE_FAIL);
            resultObj.setMsg(runTimeExcption.getMessage());
            runTimeExcption.printStackTrace();
        } catch (Exception e) {
            logger.info(e.getMessage());
            e.printStackTrace();
            resultObj.setCode(ResultObj.CODE_FAIL);
            resultObj.setMsg(e.getMessage());

        }


        //   return "redirect:" + bankUrl;
        //return new RedirectView(payParameter.getBankUrl(),true,false,false);//最后的参数为false代表以post方式提交请求
        //return new ModelAndView(new RedirectView(payParameter.getBankUrl()), payParameter.getMap());
        return resultObj.toJson();
    }



    /**
     * 提供微信订单查询接口
     * @param orderId
     * @return
     */
    @RequestMapping(value = "/queryWxOrder")
    @ResponseBody
    public String queryWxOrder(String orderId) {

        ResultObj resultObj = new ResultObj();
        resultObj.setCode(ResultObj.CODE_FAIL);
        WeChatPayServiceImpl weChatPayServiceImple = (WeChatPayServiceImpl)weChatPayService;
        System.out.println("orderId=======================>>>>"+orderId);
        try {
            Map<String, String> paymentResult = weChatPayServiceImple.queryWxOrder(orderId);
            resultObj.setCode(ResultObj.CODE_SUCCESS);
            resultObj.setData(paymentResult);
        } catch (MyRunTimeExcption e) {
            logger.warn(e.getMessage());
            resultObj.setMsg(e.getMessage());
        } catch (Exception e) {
            logger.warn(e.getMessage());
            resultObj.setMsg(e.getMessage());

        }
        return resultObj.toJson();
    }

    /**
     * 根据内容生成二维码
     * @param request
     * @param response
     */
    @RequestMapping(value = "/getTwoDimensionCode")
    public void getTwoDimensionCode(HttpServletRequest request, HttpServletResponse response) {

        String codeUrl = request.getParameter("codeUrl");
        logger.warn("【进入生成二维码的控制层。。。。。。】");

        try {
            TwoDimensionCode.toImage(
                    codeUrl,
                    TwoDimensionCode.PIC_WIDTH,
                    TwoDimensionCode.PIC_HEIGHT,
                    TwoDimensionCode.PicTypeEnum.JPG,
                    response.getOutputStream()
            );
        } catch (IOException e) {
            logger.warn("【输出二维码失败。。。。。。】");
            logger.warn("【" + e.getMessage() + "】。。。。。。");
        } catch (Exception e) {
            logger.warn("【输出二维码失败。。。。。。】");
            logger.warn("【" + e.getMessage() + "】。。。。。。");
        }
    }


    @RequestMapping(value = "/notificationFromAliPay")
    public ModelAndView notificationFromAliPay(HttpServletRequest request) {
        logger.info("notificationFromAliPay=============>>>>");
        ModelAndView m = new ModelAndView();
        m.setViewName("/web/pay/payResult");
        try {
            Map<String,String> map=this.showRequestParameters(request);
            aliPayService.notification(map);
            String orderId=map.get("out_trade_no");
            Order order=orderService.getOrderById(Long.parseLong(orderId));
            m.addObject("order",order);
            m.addObject("code", ResultObj.CODE_SUCCESS);
        } catch (MyRunTimeExcption runTimeExcption) {
            runTimeExcption.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
            m.addObject("code", ResultObj.CODE_FAIL);
        }
        return m;
    }



    /**
     * 客户支付后微信的回调接口
     * @param request
     * @return
     */
    @RequestMapping(value = "/notification")
    @ResponseBody
    public String notification(HttpServletRequest request) {

        InputStream inputStream = null;
        BufferedReader bufferedReader = null;

        try {
            inputStream = request.getInputStream();
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));

            String str;
            StringBuilder xmlString = new StringBuilder();
            while ((str = bufferedReader.readLine()) != null) {
                xmlString.append(str);
            }
            try {
                bufferedReader.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            Map<String, String> xml = new HashMap<String, String>();
            xml.put("xml", xmlString.toString());
            Map<String, String> returnMap = weChatPayService.notification(xml);
            return returnMap.get("xml");
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }



    @RequestMapping(value = "/{orderId}")
    public ModelAndView pay(HttpServletRequest request,@PathVariable("orderId") Long orderId) {        // source: 1(来源于网站) | 2(来源于微站)
        ModelAndView mov = new ModelAndView();
        mov.setViewName("/web/pay/pay");

        if(super.getIsMobile(request)){
            mov.setViewName("/wap/pay/pay");
        }
        Order order=orderService.getOrderById(orderId);
      mov.addObject("order",order);
        return mov;
    }

    /**
     * 支付结果
     * @param errorStr
     * @param errorCode
     * @return
     */
    @RequestMapping(value = "/payResult")
    public ModelAndView paySuccess(HttpServletRequest request,String errorStr,String errorCode,Long ordrId) {
        // source: 1(来源于网站) | 2(来源于微站)
        ModelAndView mov = new ModelAndView();
        mov.setViewName("/web/pay/payResult");
        if(super.getIsMobile(request)){
            mov.setViewName("/wap/pay/payResult");
        }
        Order order=orderService.getOrderById(ordrId);
        mov.addObject("errorStr",errorStr);
        mov.addObject("errorCode",errorCode);
        mov.addObject("order",order);
        return mov;
    }

    //将前缀为consigneeInfo.的属性绑定到 名称为consigneeInfo的对象
    @InitBinder("consigneeInfo")
    public void initBinder2(WebDataBinder binder){
        binder.setFieldDefaultPrefix("consigneeInfo.");
    }
}
